package com.example.spring_blog.common.interceptor;

import com.example.spring_blog.common.constant.Constants;
import com.example.spring_blog.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 在controller层接收请求之前拦截器开始进行拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userToken = request.getHeader(Constants.USER_TOKEN_HEADER_KEY);
        log.info("从header中获取userToken:{}", userToken);
        // 如果没有拿到用户头部的token
        if (userToken == null) {
            response.setStatus(401); // 401 表示用户未成功登录
            return false;
        }

        // 校验token是否合法
        Claims claims = JwtUtils.parseJwt(userToken);
        if (claims == null) {
            response.setStatus(401); // 401 表示用户未成功登录
            return false;
        }
        return true;
    }
}
